//
//  QDLoginCodeViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/27.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit

/// 验证时间的key
let CodeRegisterTimerKey = "RegisterTimerKey";


/// 二维码验证
final class QDLoginCodeViewController: NWViewController,QDTimeVerifier {

    /// 返回的回调
    var backHandler:((Int)->Void)?
    
    /// 手机号
    var phone: String = ""
    /// 返回按钮
    private let backButton = UIButton()
    /// 大标题的标签
    private let largeTitleLabel = UILabel()
    /// 验证码已发送至手机尾号xxxx
    private let subtitleLabel = UILabel()
    /// 验证码界面
    private let codeInputView = CRBoxInputView()
    /// 发送二维码的按钮
    private let sendButton = UIButton()
    /// 是否应该自动发送
    private let shouldAutoSend = true
    /// 用于记录当前的秒数
    private var distance = 0
    /// 计时器
    private var timer: Timer?
    /// 是否正在登陆
    private var isLoging: Bool = false
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        hbd_backInteractive = false //屏蔽返回手势
        
        backButton.backgroundColor = .clear
        backButton.adjustsImageWhenHighlighted = false
        backButton.setImage("login_back".namedImage, for: .normal)
        backButton.addTarget(self, action: #selector(back), for: .touchUpInside)
        
        largeTitleLabel.text = "输入验证码"
        largeTitleLabel.textColor = QDColors.black
        largeTitleLabel.font = Font.semibold.font(size: 28)
        
        let phone = self.phone as NSString
        subtitleLabel.text = "验证码已发送至尾号\(phone.length >= 4 ? phone.substring(from: phone.length - 4) : "")的手机"// 针对线上崩溃，进行安全监测
        subtitleLabel.textColor = QDColors.black
        subtitleLabel.font = Font.light.font(size: 16)
        
        codeInputView.codeLength = 6
        codeInputView.customCellProperty.cellBgColorNormal = #colorLiteral(red: 0.7607843137, green: 0.768627451, blue: 0.7647058824, alpha: 1)
        codeInputView.customCellProperty.cellBorderColorSelected = #colorLiteral(red: 0.5921568627, green: 0.6, blue: 0.5960784314, alpha: 1)
        codeInputView.customCellProperty.cellBgColorNormal = .white
        codeInputView.customCellProperty.cellBgColorSelected = .white
        codeInputView.customCellProperty.borderWidth = 1
        codeInputView.customCellProperty.cellCursorColor = QDColors.theme
        codeInputView.customCellProperty.cellFont = Font.medium.font(size: 20)
        codeInputView.customCellProperty.cellTextColor = QDColors.black
        codeInputView.boxFlowLayout.itemSize = CGSize(width: 43, height: 56)
        codeInputView.loadAndPrepare(withBeginEdit: true)
        codeInputView.textDidChangeblock = { [unowned self](text, finish) in
            if finish && !self.isLoging {
                self.isLoging = true
                self.login()
            }
        }
        
        sendButton.setTitleColor(#colorLiteral(red: 0.3215686275, green: 0.8, blue: 0.4156862745, alpha: 1), for: .normal)
        sendButton.setTitleColor(#colorLiteral(red: 0.7607843137, green: 0.768627451, blue: 0.7647058824, alpha: 1), for: .disabled)
        sendButton.setTitle("点击重新获取", for: .normal)
        sendButton.titleLabel?.font = Font.regular.font(size: 14)
        sendButton.addTarget(self, action: #selector(sendCode), for: .touchUpInside)
        sendButton.isEnabled = false //默认不能使用
        
        view.addSubview(backButton)
        view.addSubview(largeTitleLabel)
        view.addSubview(subtitleLabel)
        view.addSubview(codeInputView)
        view.addSubview(sendButton)
        
        backButton.snp.makeConstraints { (make) in
            make.width.height.equalTo(32)
            make.top.equalToSuperview().offset(57 + BarDistance.NavigationBar.safeDistance)
            make.left.equalToSuperview().offset(10)
        }
        
        largeTitleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.height.equalTo(40)
            make.top.equalTo(backButton.snp.bottom).offset(36)
        }
        
        subtitleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.top.equalTo(largeTitleLabel.snp.bottom).offset(8)
            make.height.equalTo(22)
        }
        
        codeInputView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().inset(20)
            make.height.equalTo(56)
            make.top.equalTo(subtitleLabel.snp.bottom).offset(40)
        }
        
        sendButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(codeInputView.snp.bottom).offset(24)
        }
        
        /// 合法
        if phone.length >= 4 {
            // 发送二维码
            sendCode()
        }else { // 针对线上崩溃，进行安全监测
            view.showTextHUD(text: "手机号有误!")
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        timer?.invalidate()
        timer = nil
    }
    
    
    /// 导航返回
    @objc func back(){
        navigationController?.popViewController(animated: true)
        backHandler?(distance)
    }
    
    
    // MARK: NavigationBar
    
    /// 导航栏隐藏
    override var nav_barHidden: Bool { return true }

    // MARK: 发送验证码
    
    /// 发送验证码
    @objc func sendCode(){
    
        //立马变为不可用
        sendButton.isEnabled = false
        sendButton.setTitle("\(self.limitTime)秒后重新发送", for: .disabled)
        
        //进行验证码的请求
        QDNetworkingManager.request(url: sendMsgUrl, paramteres: ["Type":"1","Id":"66668888","Phone":phone], success: { (msg,data) in
            self.view.showTextHUD(text: msg) // 显示提示
            //如果成功了，进行本地写入
            self.saveCurrentTime(key: CodeRegisterTimerKey)
            //进行计时器
            self.startTimer(compareTime: self.time(key: CodeRegisterTimerKey))
            
        }) { (errorMsg, errorType) in
    
            self.view.showTextHUD(text: errorMsg)
            self.sendButton.isEnabled = true
        }
    }

    /// 开始计时器检测
    func startTimer(compareTime: Int) {
        
        if self.timer != nil {
            return;
        }
        
        // 开启轮训
        self.timer = RITLTimer.scheduledTimer(withTimeInterval: 1.0, userInfo: [:], repeats: true, blockHandle: { [weak self] (_) in
            
            guard let strongSelf = self else { return }
            
            //获得当前时间
            let currentTime = Int(Date().timeIntervalSince1970)
            let distance = currentTime - compareTime
            
            if distance >= strongSelf.limitTime {//表示验证码可以进行
                strongSelf.timer!.invalidate()
                strongSelf.timer = nil
                strongSelf.sendButton.isEnabled = true
            }else {//表示做限制
                strongSelf.sendButton.isEnabled = false
                strongSelf.distance = strongSelf.limitTime - distance
                strongSelf.sendButton.setTitle("\(strongSelf.distance)秒后重新发送", for: .disabled)
            }
        })
    }
    
    // MARK: 登陆
    
    /// 进行登录
    func login() {
        
        view.showTextHUD(text: "正在登陆",delayHidden: 10)
        view.endEditing(true)
        
        // 进行登录请求"
        QDNetworkingManager.request(url: loginUrl, method: .POST, paramteres: ["Id":"66668888","Phone":phone,"Code": codeInputView.textValue ?? ""], success: { (msg, data) in
            
            //实例化本地model
            if let userModel = QDUserInfoModel.deserialize(from: data) {
                
                userModel.saveToNativePlace()//存储本地
                QDUserInfoModel.readFromNativePlace()//读取信息
                QDUserStatus.isLogin = true//更新登陆状态
                QDUserStatus.isNFC = userModel.isNFC()//记录是否是NFC
            }
            
            
            QDUMEventManager.event(event: .login)
            //获得数据，登陆成功
            self.view.showTextHUD(text: "登陆成功")
            //修改标志位
            self.isLoging = false
            //消失
            self.dismiss(animated: true, completion: nil)
            
        }) { (errorMsg, errorType) in
            
            //修改标志位
            self.isLoging = false
            //清除二维码
            self.codeInputView.clearAll()
            self.view.showTextHUD(text: errorMsg)
        }
    }
}

